const {
  pinyin,
  customPinyin,
  addDict,
  clearCustomDict,
} = require("pinyin-pro");
const fs = require("fs");
const path = require("path");
const xlsx = require("node-xlsx");
const { shell, ipcRenderer, remote } = require("electron");
const { dialog } = require("@electron/remote");
const { baidu, modern, complete } = require("./loadDict");
const store = require("./store.js");
let templateFilePath, templateFilePath2;
//每次启动应用时，读取配置拼音
ipcRenderer.send("checkPackaged");
ipcRenderer.on("getPackaged", (event, isPackaged) => {
  templateFilePath = path.join(process.cwd(), "/extraResources", "custom.xlsx");
  ipcRenderer.send("sendCustomFilePath", templateFilePath);
  templateFilePath2 = path.join(
    process.cwd(),
    "/extraResources",
    "persons.xlsx"
  );
  if (isPackaged) {
    templateFilePath = path.join(
      process.cwd(),
      "/resources/extraResources",
      "custom.xlsx"
    );
    templateFilePath2 = path.join(
      process.cwd(),
      "/resources/extraResources",
      "persons.xlsx"
    );
  }
  window.templateFilePath = templateFilePath;
  window.templateFilePath2 = templateFilePath2;
  let persons = loadCustomPinyin(templateFilePath2);
  let custom = loadCustomPinyin(templateFilePath);

  let dictSet = {
    baidu,
    modern,
    complete,
    persons
  }
  let { dicts } = store.get("setting");
  dicts = dicts.sort((a, b) => a.priority - b.priority);
  dicts.forEach((d) => {
    if(d.name !== "custom"){
      d.isUsing ? addDict(dictSet[d.name]) : ""
    }else{
      d.isUsing ? customPinyin(custom) : ""
    }
  });
  // addDict(ModernChineseDict)
  // addDict(CompleteDict)
  // addDict(baidu)
  // addDict(custom1)
  // customPinyin(custom);
  let watching = false;
  try {
    fs.watch(templateFilePath, (eventType, fileName) => {
      if (watching && eventType !== "change") return;
      watching = true;
      clearCustomDict("pinyin");
      customPinyin(loadCustomPinyin(templateFilePath)); //每次文件保存执行
      //自动渲染测试拼音
      let testSpan = document.querySelector(".test-result");
      let testInput = document.querySelector(".test-text");
      if (testSpan.innerText.length !== 0 && testInput.value.length < 9) {
        document.querySelector(".test-result").innerText = pinyin(
          testInput.value
        );
      }
      setTimeout(() => {
        watching = false;
      }, 100);
    });
  } catch (e) {
    //TODO handle the exception
    console.log("e.message", e.message);
  }
});

let loadCustomPinyin = (path) => {
  let list = xlsx.parse(path);
  let presetPinyin = {};
  if (list) {
    list = list[0].data;
    for (let i = 0; i < list.length; i++) {
      if (list[i].length == 0 || !list[i][0] || !list[i][1]) {
        list.splice(i, 1);
        i--;
      }
    }
    list.forEach((item) => {
      presetPinyin[item[0]] = item[1];
    });
  }
  return presetPinyin;
};

let handleImport = () => {
  let { importMode } = store.get("setting");
  if (importMode !== "add") {
    if (
      !confirm("警告：覆盖原有数据可能无法找回，建议先进行下载备份\n是否继续？")
    )
      return;
  }
  dialog
    .showOpenDialog({
      title: "选择excel文件",
      buttonLabel: "确定",
    })
    .then((res) => {
      if (!res.canceled) {
        let filepath = res.filePaths[0];
        let type = filepath.split(".").at(-1);
        if (!["xlsx", "xls"].includes(type)) {
          alert("仅支持导入xlsx、xls后缀的excel文件");
        } else {
          let buffer;
          if (isAdd) {
            let originList = xlsx.parse(window.templateFilePath);
            let list = xlsx.parse(filepath);
            let newList = [
              {
                name: "sheet1",
                data: [...originList[0].data, ...list[0].data],
              },
            ];
            buffer = xlsx.build(newList);
          } else {
            let list = xlsx.parse(filepath);
            buffer = xlsx.build(list);
          }
          fs.writeFile(window.templateFilePath, buffer, (err) => {
            // console.log(err)
            if (err) {
              if (err.message.includes("resource busy or locked"))
                alert("导入失败，请先关闭exe内部excel文件");
              else alert(`导入失败：${err.message}`);
            }
            customPinyin(loadCustomPinyin(templateFilePath));
            alert("导入成功");
          });
        }
      }
    })
    .catch((err) => {
      alert(`选择文件错误：${err.message.toString()}`);
      // console.log("err", err.message);
    });
};

let handleDownload = () => {
  let file = fs;
  // let url = path.join(__dirname, 'custom.xlsx')
  // 创建一个<a>标签
  const element = document.createElement("a");
  // 设置href属性为下载链接
  element.setAttribute("href", window.templateFilePath);
  // 设置download属性为文件名
  element.setAttribute("download", "custom");
  // 将<a>标签添加到DOM中
  document.body.appendChild(element);
  // 模拟点击<a>标签开始下载
  element.click();
  // 从DOM中移除<a>标签
  document.body.removeChild(element);
};
let handleEdit = () => {
  // let url = path.join(__dirname, 'custom.xlsx')
  console.log(window.templateFilePath);
  if (/[\u4e00-\u9fa5]+/g.test(window.templateFilePath)) {
    alert("打开失败，exe路径中不能包含中文字符");
  }
  shell.openExternal("file:///" + window.templateFilePath);
};

module.exports = { handleImport, handleDownload, handleEdit, loadCustomPinyin };
